//
//  hotDiscussViewController.m
//  LT
//
//  Created by dllo on 16/5/23.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "hotDiscussViewController.h"
#import "hotDiscussTableViewCell.h"
#import "hotDiscussImageTableViewCell.h"
#import "hotDisModel.h"
#import "ZHNetworking.h"
#import "hotDisDetailViewController.h"


static NSString *const HotDisImageTabelCell = @"HotDisImageTableCell";
static NSString *const HotDisTabelCell = @"HotDisTableCell";

@interface hotDiscussViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchResultsUpdating>

@property(nonatomic,strong)UITableView *hotDiscussTableView;
//这个myArray是要确定多少行Row的array
@property(nonatomic,strong)NSMutableArray *myArray;



//先建立一个搜索的数组
@property(nonatomic,strong)NSMutableArray *searchArray;

//放缓存的数组
@property(nonatomic,strong)NSMutableArray *readArray;


@end

@implementation hotDiscussViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myArray = [NSMutableArray array];
    [self read];
    [self getData];
    //缓存读取数据
  
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blueColor];
    
    self.hotDiscussTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 108) style:UITableViewStylePlain];
    [self.view addSubview:self.hotDiscussTableView];
    self.hotDiscussTableView.delegate = self;
    self.hotDiscussTableView.dataSource = self;
    self.hotDiscussTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //不能取消
    self.hotDiscussTableView.scrollEnabled = YES;
    
    self.searchArray = [NSMutableArray array];
    
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    //代理
    self.searchController.searchResultsUpdater = self;
    //    设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
    self.searchController.dimsBackgroundDuringPresentation = NO;

    //吧搜索栏加在view的头视图上
    self.hotDiscussTableView.tableHeaderView = self.searchController.searchBar;
    
    //注册俩种cell

    [self.hotDiscussTableView registerClass:[hotDiscussTableViewCell class] forCellReuseIdentifier:HotDisTabelCell];
    [self.hotDiscussTableView registerClass:[hotDiscussImageTableViewCell class]forCellReuseIdentifier:HotDisImageTabelCell];
    
    //这句防止搜索框跟着其他俩个界面走
    self.definesPresentationContext = YES;
    
}

//cell点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //建立跳转详情界面的对象
    hotDisDetailViewController *hotDetailVC = [[hotDisDetailViewController alloc]init];
    //每一个model对应一个数组中的一行
    hotDisModel *model = [self.myArray objectAtIndex:indexPath.row];
    
    //这里从数组取出来的model的东西赋值给在详情界面的.h界面建立的model
    hotDetailVC.hotDisModel = model;
    
    //带绿框跳转用UINavigationController
    UINavigationController *hotDetailNa = [[UINavigationController alloc]initWithRootViewController:hotDetailVC];
    

    
    [self presentViewController:hotDetailNa animated:YES completion:^{
        
        
    }];
    //详情的model就是myArray数组中的每一个对应小字典
    hotDisModel *hotModel = [self.myArray objectAtIndex:indexPath.row];
  
    //标题title就是model的title
    hotDetailVC.navigationItem.title = hotModel.title;
    
    hotDetailVC.hotDisDetailString = hotModel.appview_url;
 
    
}

-(void)read{

    //取数据从本地plist
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *hotDiscussPath = [path stringByAppendingPathComponent:@"hotDiscuss.plist"];
    NSArray *localHotDiscussArray = [NSArray arrayWithContentsOfFile:hotDiscussPath];
    if (localHotDiscussArray.count != 0) {
        for (NSDictionary *dic in localHotDiscussArray) {
            hotDisModel *model = [[hotDisModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.myArray addObject:model];
            
        }
    }



}


-(void)getData{
    
    //GET请求
    [ZHNetworking zhGETWithURL:@"http://open.qyer.com/qyer/community/hotbbs/index?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&lat=38.88283798007659&lon=121.539156053574&oauth_token=4ea07b0d41e13f5cb1448a45a3613e45&page=1&track_app_channel=App%2520Store&track_app_version=6.9.0&track_device_info=iPhone8%2C1&track_deviceid=F417850E-117E-4BF4-AAA6-3AD14E14E3C1&track_os=ios%25209.3.1&track_user_id=7891151&v=1" parameter:nil succes:^(id result) {
        
        //之前上面没有初始化数组导致这里崩溃了
        NSArray *dataArray = [result objectForKey:@"data"];
        
        //写入缓存
        //找到document路径
        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        NSLog(@"%@",path);//打印的目的是为了确定这个路径对不对
        //拼接一个自己的路径
        NSString *hotDiscussPath = [path stringByAppendingPathComponent:@"hotDiscuss.plist"];
        //写入数据到对应路径的plist文件中
        [dataArray writeToFile:hotDiscussPath atomically:YES];
        
        
        for (NSDictionary *dic in dataArray) {
            hotDisModel *model = [[hotDisModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.myArray addObject:model];
            
            }
        //刷新tableView
        [self.hotDiscussTableView reloadData];
        
    } failure:^(NSError *error) {
        
        
    }];
    
    }


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    hotDisModel *model = [[hotDisModel alloc]init];
    if (self.searchController.active) {//搜索的时候返回高度
         
    
    if (model.bigpic_arr == nil) {
        return 250* WIDTHCELL;
    }
    return 450 * WIDTHCELL;
    
    }else
    {
        if (model.bigpic_arr == nil) {
            return 250* WIDTHCELL;
        }
        return 450* WIDTHCELL;
    
    
    }
    
}

#pragma mark tableView每个分区要显示的行数(cell的个数)必须实现的方法之一
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.searchController.active)
    {
        return  self.searchArray.count;
    }
    
        return self.myArray.count;
    
}

#pragma mark 必须实现的方法之2,作用是每显示一个cell都会执行这个方法.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.searchController.active) {
        hotDisModel *model = [self.searchArray objectAtIndex: indexPath.row];
        //NSMutableArray *tempArray = model.bigpic_arr;
       
        if (model.bigpic_arr == nil) {
            
            hotDiscussTableViewCell *cellOne = [tableView dequeueReusableCellWithIdentifier:HotDisTabelCell forIndexPath:indexPath];
            
            
            
            cellOne.model = model;
            return cellOne;
            
            
        }else{
            
            hotDiscussImageTableViewCell *cellTwo = [tableView dequeueReusableCellWithIdentifier:HotDisImageTabelCell forIndexPath:indexPath];
            
            cellTwo.model = model;
            
            return cellTwo;
            
        }

    
    }
    
    else
    {
      hotDisModel *model = [self.myArray objectAtIndex:indexPath.row];
    
        if (model.bigpic_arr == nil) {
            
            hotDiscussTableViewCell *cellOne = [tableView dequeueReusableCellWithIdentifier:HotDisTabelCell forIndexPath:indexPath];
            
            cellOne.model = model;
            return cellOne;
            
            
    }else{
            
            hotDiscussImageTableViewCell *cellTwo = [tableView dequeueReusableCellWithIdentifier:HotDisImageTabelCell forIndexPath:indexPath];
            
            cellTwo.model = model;
            
            return cellTwo;
            
        }
    
    }
}
  
    
    




-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
        
        NSString *searchString = [self.searchController.searchBar text];
        
        //    NSLog(@"===%@",searchString);
        
        [self.searchArray removeAllObjects];
        for (hotDisModel *model in self.myArray) {
            
            //rangeOfString:方法是在movieName中搜索是否包含searchText
            //rangeOfString 前面的参数是要被搜索的字符串，后面的是要搜索的字符
            //NSNotFound 表示请求操作的某个内容没有发现
            if ([model.title rangeOfString:searchString].location != NSNotFound) {
                
                [self.searchArray addObject:model];
            }
        }
        //    NSLog(@"searchArray===%@",self.searchArray);
        
        [self.hotDiscussTableView reloadData];
        
    }
    
//UISearchController的移除
//在viewWillDisappear中要将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    if (self.searchController.active) {
        
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
        
    }
}
    
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
